<template>
  <div id="gptStaffIndex">
    <el-row>
      <!-- 表格查询条件 -->
      <el-col :span="24">
        <el-form :inline="true" ref="stationForm" :model="queryForm">
          <el-form-item>
            <el-input v-model="queryForm.userName" placeholder="账号邮箱"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryForm.nikeName" placeholder="账号昵称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryForm.activationCode" placeholder="当前使用的激活码"></el-input>
          </el-form-item>
          <el-form-item>
            <gd_param type="select"
                      paramCode="gptVipType"
                      placeholder="会员类型"
                      v-model="queryForm.staffStateCode"/>
          </el-form-item>
          <el-form-item>
            <gd_param type="select"
                      paramCode="isOrNot"
                      placeholder="会员是否可用"
                      v-model="queryForm.vipIsCanUse"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getTableDatas()">查询</el-button>
            <el-button @click="resetQueryForm" icon="el-icon-refresh-right">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <!-- 数据表格 -->
      <el-col :span="24">
        <el-row>
          <el-col :span="24">
            <!--            <el-button type="primary" icon="el-icon-plus" @click="dialog.saveOrEditDiv=true">新增模型</el-button>-->
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="moreDeletes">
              <el-button slot="reference" type="danger" icon="el-icon-delete">批量删除账号</el-button>
            </el-popconfirm>
          </el-col>
        </el-row>
        <el-row style="margin-top:10px;">
          <el-col :span="24">
            <el-table :data="tableData" border style="width: 100%" @selection-change="tableDataSelected">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="userName" label="账号"></el-table-column>
              <el-table-column prop="nikeName" label="昵称"></el-table-column>
              <el-table-column prop="staffStateName" label="会员类型" width="110">
                <template slot-scope="scope">
                  <el-tag :type="getTagType(scope.row.staffStateCode)">{{ scope.row.staffStateName }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="会员时间">
                <template slot-scope="scope">
                  {{ scope.row.vipStartTime | timeFormat }} 至 {{ scope.row.vipEndTime | timeFormat }}
                </template>
              </el-table-column>
              <el-table-column label="会员状态" width="90">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.vipIsCanUse==1" type="success">正常</el-tag>
                  <el-tag v-else type="danger">过期</el-tag>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center" width="180">
                <template slot-scope="scope">
                  <el-button @click="rowShow(scope.row)" size="small" icon="el-icon-search" circle
                             title="查看"></el-button>
                  <el-button @click="rowEdit(scope.row)" type="primary" size="small" icon="el-icon-edit" circle
                             title="编辑"></el-button>
                  <el-button @click="rowDelete(scope.row)" type="danger" icon="el-icon-delete" size="small" circle
                             title="删除"></el-button>
                  <el-dropdown>
                    <span class="el-dropdown-link"><i class="el-icon-arrow-down el-icon--right"></i></span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item><span @click="rowStaffInfos(scope.row)">用户操作记录</span></el-dropdown-item>
                      <el-dropdown-item><span @click="rowResetDay(scope.row)">当日次数重置</span></el-dropdown-item>
                      <el-dropdown-item><span @click="rowGrantUpdate(scope.row)">授权信息修改</span></el-dropdown-item>
                      <el-dropdown-item><span @click="rowActiveCode(scope.row)">激活卡激活</span></el-dropdown-item>
                      <el-dropdown-item><span @click="rowPwdChange(scope.row)">重置密码</span></el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              @size-change="tableSizeChange"
              @current-change="tableCurrentChange"
              :current-page="pageData.page"
              :page-sizes="[10, 20, 40, 100]"
              :page-size="pageData.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageData.total"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 新增\修改用户信息弹窗 -->
    <el-dialog
      :title="(dialog.isEdit == true ? '编辑' : '新增') + '模型'"
      :visible.sync="dialog.saveOrEditDiv"
      :close-on-click-modal="false"
      :show-close="false"
      width="70%"
      :destroy-on-close="true"
    >
      <el-form
        ref="saveOrEditDataForm"
        :rules="saveOrEditDataFormRules"
        :model="saveOrEditData"
        label-width="110px"
      >
        <el-form-item label="账号邮箱" prop="userName">
          <el-input
            v-model="saveOrEditData.userName"
            placeholder="请填写账号邮箱"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nikeName">
          <el-input
            v-model="saveOrEditData.nikeName"
            placeholder="请填写昵称"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="会员开始时间" prop="vipStartTime">
          <el-date-picker
            v-model="saveOrEditData.vipStartTime"
            type="datetime"
            placeholder="选择会员开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员结束时间" prop="vipEndTime">
          <el-date-picker
            v-model="saveOrEditData.vipEndTime"
            type="datetime"
            placeholder="选择会员开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="账号是否可用" prop="vipIsCanUse">
          <gd_param type="select"
                    paramCode="isOrNot"
                    placeholder="会员是否可用"
                    v-model="saveOrEditData.vipIsCanUse" />
        </el-form-item>

        <!-- 按钮组 -->
        <div style="margin-top: 10px">
          <el-button type="primary" @click="submitSaveOrEdit" :loading="formLoading">确定</el-button>
          <el-button
            @click="
							dialog.saveOrEditDiv = false;
              dialog.isEdit = false;
							resetAddOrEditOrShowForm();
						"
          >
            取消
          </el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      title="用户详情"
      :visible.sync="dialog.showDiv"
      width="85%"
      :show-close="false"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-descriptions class="margin-top" :column="3" border>
        <el-descriptions-item label="账户邮箱">{{ showData.staff.userName }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ showData.staff.nikeName }}</el-descriptions-item>
        <el-descriptions-item label="会员类型">{{ showData.staff.staffStateName }}</el-descriptions-item>
        <el-descriptions-item label="会员开始时间">{{ showData.staff.vipStartTime | timeFormat }}</el-descriptions-item>
        <el-descriptions-item label="会员结束时间">{{ showData.staff.vipEndTime | timeFormat }}</el-descriptions-item>
        <el-descriptions-item label="账号状态">
          <el-tag v-if="showData.staff.vipIsCanUse==1" type="success">正常</el-tag>
          <el-tag v-else type="danger">过期</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="当前激活码">{{ showData.staff.activationCode }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ showData.staff.comment }}</el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="left">授权模型</el-divider>
      <el-table :data="showData.grantList" style="width: 100%">
        <el-table-column prop="modelsName" label="模型名称"></el-table-column>
        <el-table-column prop="modeGrantUseTypeName" label="授权类别"></el-table-column>
        <el-table-column prop="dayLimitCount" label="日上限">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.dayLimitCount==-1" type="warning">无上限</el-tag>
            <el-tag v-if="scope.row.dayLimitCount==0" type="danger">未开通</el-tag>
            <el-tag v-if="scope.row.dayLimitCount!=0&&scope.row.dayLimitCount!=-1" type="success">
              {{ scope.row.dayLimitCount }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="useLess" label="现在剩余">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.useLess==-1" type="warning">无上限</el-tag>
            <el-tag v-if="scope.row.useLess==0" type="danger">0</el-tag>
            <el-tag v-if="scope.row.useLess!=0&&scope.row.useLess!=-1" type="success">{{ scope.row.useLess }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        @click="
							dialog.showDiv = false;
							resetAddOrEditOrShowForm();
						"
      >
        关闭
      </el-button>
    </el-dialog>

    <!-- 用户操作记录 -->
    <el-dialog
      title="用户详情"
      :visible.sync="dialog.infos"
      width="85%"
      :show-close="false"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-table :data="staffInfos" style="width: 100%" height="300">
        <el-table-column prop="infoTime" label="日期" width="180">
          <template slot-scope="scope">
            {{ scope.row.infoTime | timeFormat }}
          </template>
        </el-table-column>
        <el-table-column prop="infoDesc" label="记录"></el-table-column>
      </el-table>
      <el-button
        @click="
							dialog.infos = false;
							resetAddOrEditOrShowForm();
						"
      >
        关闭
      </el-button>
    </el-dialog>

    <!-- 授权信息修改 -->
    <el-dialog
      title="授权信息修改"
      :visible.sync="dialog.grants"
      width="90%"
      :show-close="false"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-table :data="updateStaffGrantData.grants" border style="width: 100%">
        <el-table-column prop="modelsName" label="模型名称"></el-table-column>
        <el-table-column prop="modeGrantUseTypeCode" label="授权类型">
          <template slot-scope="scope">
            <el-select v-model="scope.row.modeGrantUseTypeCode" placeholder="请选择授权类别">
              <el-option
                v-for="item in paramsData.modeGrantUseType"
                :key="item.dataValue"
                :label="item.dataName"
                :value="item.dataValue">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="isHaveDayLimit" label="是否有每日上限" width="80">
          <template slot-scope="scope">
            <el-switch
              @change="rowIsHaveDayLimitChange(scope.row)"
              v-model="scope.row.isHaveDayLimit"
              active-value="1"
              inactive-value="0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="dayLimitCount" label="每日上限设置(“-1”代表无上限)">
          <template slot-scope="scope">
            <el-input-number :disabled="scope.row.isHaveDayLimit!=1?true:false" v-model="scope.row.dayLimitCount"  :min="-1" :max="9999"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="useLess" label="当日剩余">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.useLess" :disabled="scope.row.isHaveDayLimit!=1?true:false"  :min="-1" :max="9999"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary"
        @click="saveUpdateGrants"
      >
        保存
      </el-button>
      <el-button
        @click="
							dialog.grants = false;
							updateStaffGrantData.grants = [];
						"
      >
        关闭
      </el-button>
    </el-dialog>

    <!-- 激活卡激活 -->
    <el-dialog
      title="激活卡激活"
      :visible.sync="dialog.activeCode"
      width="85%"
      :show-close="false"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="activeCodeDataForm"
        :rules="activeCodeDataFormRules"
        :model="activeCodeData"
        label-width="110px"
      >
        <el-form-item label="激活卡号" prop="activeCode">
          <el-input
            v-model="activeCodeData.activeCode"
            placeholder="请填写激活卡号"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary"
                 @click="saveActiveCode"
      >
        激活
      </el-button>
      <el-button
        @click="
							dialog.activeCode = false;
							activeCodeData = {};
						"
      >
        关闭
      </el-button>
    </el-dialog>

  </div>
</template>

<script>
import * as axiosAPI from '@/api/gpt/gptstaff.js';
import * as activeCodeAxiosAPI from '@/api/gpt/activeCode.js';
import * as paramAPI from '@/api/param.js';
import gd_param from "@/components/mycomponents/gd_param.vue";
import gd_file from "@/components/mycomponents/gd_file.vue";

export default {
  name: 'gptStaffIndex',
  components: {gd_file, gd_param},
  data() {
    return {
      //查询表单数据
      queryForm: {
        userName: null,
        nikeName: null,
        activationCode: null,
        staffStateCode: null,
        vipIsCanUse: null,
        vipStartTime: null,
        vipEndTime: null
      },
      //表格数据
      tableData: [],
      //主表-分页数据
      pageData: {
        page: 1,
        size: 10,
        total: 0
      },
      //当前表格复选数据
      nowTableSelected: [],
      //弹窗状态
      dialog: {
        isEdit: false,
        saveOrEditDiv: false,
        showDiv: false,
        infos: false,
        grants: false,
        activeCode: false
      },
      //添加编辑表单-检验
      saveOrEditDataFormRules: {
        userName: {required: true, message: '请输入账号邮箱', trigger: 'blur'},
        nikeName: {required: true, message: '请输入昵称', trigger: 'blur'},
        vipStartTime: {required: true, message: '请选择会员开始时间', trigger: 'change'},
        vipEndTime: {required: true, message: '请选择会员结束时间', trigger: 'change'},
        vipIsCanUse: {required: true, message: '请选择账号状态', trigger: 'change'}
      },
      // 激活卡表单验证
      activeCodeDataFormRules:{
        activeCode:{required: true, message: '请输入激活卡号', trigger: 'blur'}
      },
      saveOrEditData: {
        staffID: null,
        comment: null,
        userName: null,
        nikeName: null,
        pwd: null,
        activationCode: null,
        invitationCode: null,
        telNumber: null,
        staffStateCode: null,
        staffStateName: null,
        vipStartTime: null,
        vipEndTime: null,
        vipIsCanUse: null
      },
      //展示表单数据
      showData: {
        staff: {},
        grantList: []
      },
      // 个人操作记录
      staffInfos: [],
      // 修改个人授权列表项目
      updateStaffGrantData: {
        grants: []
      },
      // 激活卡表单
      activeCodeData:{
        staffID:null,
        staffName:null,
        activeCode:null
      },
      //表单加载值
      formLoading: false,
      // 字典数据
      paramsData:{
        modeGrantUseType:[]
      }
    };
  },
  mounted() {
    this.getTableDatas();
    this.getParamDatasModeGrantUseType();
  },
  filters: {
    timeFormat: function (value) {
      let date = new Date(value);
      let year = date.getFullYear();
      let month = date.getMonth() + 1 + '';
      let day = date.getDate() + '';
      let hour = date.getHours() + '';
      let minute = date.getMinutes() + '';
      let second = date.getSeconds() + '';
      return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')} ${hour.padStart(2, '0')}:${minute.padStart(2, '0')}:${second.padStart(2, '0')}`
    }
  },
  computed: {
    getTagType() {
      return (data) => {
        if (data == "1") {
          return "info";
        } else if (data == "2") {
          return "success";
        } else if (data == "3") {
          return "warning";
        } else if (data == "4") {
          return "danger";
        } else {
          return "ppp";
        }
      }
    }
  },
  watch: {},
  methods: {
    // 查询字典数据-模型授权使用类型
    getParamDatasModeGrantUseType(){
      let _this = this;
      paramAPI.getParamByCode("modeGrantUseType")
        .then(function(res){
          if(res.code == "0000"){
            _this.paramsData.modeGrantUseType = res.data;
          }
        })
    },
    //查询表格数据
    getTableDatas() {
      let _this = this;
      _this.queryForm.stime = null;
      axiosAPI.pages(_this.queryForm, _this.pageData)
        .then(function (response) {
          console.log(response);
          if (response.code == '0000') {
            _this.tableData = response.data.rows;
            _this.pageData.total = response.data.total;
          }
        });
    },
    //重置查询条件表单
    resetQueryForm() {
      this.queryForm = {
        userName: null,
        nikeName: null,
        activationCode: null,
        staffStateCode: null,
        vipIsCanUse: null,
        stime: null,
        vipStartTime: null,
        vipEndTime: null
      };
      this.getTableDatas();
    },
    //重置添加、编辑、展示表单
    resetAddOrEditOrShowForm() {
      this.showData = {
        staff: {},
        grantList: []
      };
      this.saveOrEditData = {
        staffID: null,
        comment: null,
        userName: null,
        nikeName: null,
        pwd: null,
        activationCode: null,
        invitationCode: null,
        telNumber: null,
        staffStateCode: null,
        staffStateName: null,
        vipStartTime: null,
        vipEndTime: null,
        vipIsCanUse: null
      }
    },
    //提交-添加、编辑表单
    submitSaveOrEdit() {
      let _this = this;
      this.$refs.saveOrEditDataForm.validate(valid => {
        if (valid) {
          this.formLoading = true;
          let _this = this;
          if (_this.dialog.isEdit == true) {// 编辑

            axiosAPI.update(_this.saveOrEditData)
              .then(function (res) {
                if (res.code == '0000') {
                  _this.dialog.saveOrEditDiv = false;
                  _this.dialog.isEdit = false;
                  _this.resetAddOrEditOrShowForm();
                  _this.formLoading = false;
                  _this.getTableDatas();
                } else {
                  _this.formLoading = false;
                }
              });

          } else { // 添加
            // axiosAPI.add(_this.saveOrEditData)
            //   .then(function(res) {
            //     if (res.code == '0000') {
            //       _this.dialog.saveOrEditDiv = false;
            //       _this.dialog.isEdit = false;
            //       _this.resetAddOrEditOrShowForm();
            //       _this.formLoading = false;
            //       _this.getTableDatas();
            //     } else {
            //       _this.formLoading = false;
            //     }
            //   });
          }
        }
      });
    },
    //提交-删除
    submitDelete(ids) {
      let _this = this;
      axiosAPI.deletes(ids)
        .then(res => {
          if (res.code == '0000') {
            _this.getTableDatas();
          }
        });
    },
    //分页条目数切换
    tableSizeChange(size) {
      this.pageData.size = size;
      this.getTableDatas();
    },
    //页码切换
    tableCurrentChange(page) {
      this.pageData.page = page;
      this.getTableDatas();
    },
    //行-查看
    rowShow(data) {
      var _this = this;
      axiosAPI.getStaffDataByID(data.staffID)
        .then(function (res) {
          if (res.code == "0000") {
            _this.showData = res.data;
            _this.dialog.showDiv = true;
          }
        });
    },
    //行-编辑
    rowEdit(data) {

      let _this = this;
      axiosAPI.getByID(data.staffID)
        .then(function (res) {
          if (res.code == "0000") {
            _this.saveOrEditData = res.data;
            _this.dialog.isEdit = true;
            _this.dialog.saveOrEditDiv = true;
          }
        });
    },
    //行-删除
    rowDelete(data) {
      this.$confirm('确定要删除这行数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitDelete(data.staffID);
      });
    },
    //点击批量删除
    moreDeletes() {
      if (this.nowTableSelected.length <= 0) {
        this.$notify.warning({
          title: '删除提示',
          message: '请至少选择一条数据再删除'
        });
        return;
      }
      let ids = '';

      for (var i in this.nowTableSelected) {
        ids += this.nowTableSelected[i].staffID + ',';
      }

      ids = ids.substring(0, ids.length - 1);

      //调用删除
      this.submitDelete(ids);
    },
    //表格批量选择
    tableDataSelected(data) {
      this.nowTableSelected = data;
    },
    // 查看用户操作信息
    rowStaffInfos(data){
      let _this = this;
      axiosAPI.getStaffInfos(data.staffID)
        .then(function(res){
          if(res.code == "0000"){
             _this.staffInfos = res.data;
             _this.dialog.infos = true;
          }
        })
    },
    // 重置用户当日使用次数
    rowResetDay(data){
      this.$confirm('确定要重置该用户当日的使用次数吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this;
        axiosAPI.staffResetUseLess(data.staffID).then(function(res){
          if(res.code == "0000"){
             _this.getTableDatas();
          }
        })
      });
    },
    // 修改用户授权信息
    rowGrantUpdate(data){
      let _this = this;
       axiosAPI.getStaffDataByID(data.staffID).then(function(res){
         if(res.code == "0000"){
            _this.updateStaffGrantData.grants = res.data.grantList;
            _this.dialog.grants = true;
         }
       })
    },
    // 激活卡激活用户
    rowActiveCode(data){
      this.activeCodeData.staffID = data.staffID;
      this.activeCodeData.staffName = data.userName;
      this.dialog.activeCode = true;
    },
    saveActiveCode(){
      let _this = this;
      this.$refs.activeCodeDataForm.validate(valid => {
        if (valid) {
          activeCodeAxiosAPI.staffActiveTheCode(_this.activeCodeData).then(function(res){
            if(res.code == "0000"){
              _this.dialog.activeCode = false;
              _this.getTableDatas();
            }
          })
        }
      });

    },
    // 重置密码
    rowPwdChange(data){
      this.$confirm('确定要重置该用户的密码?（重置密码：ailychat@123）', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var temp = {
          userName:data.userName,
          pwd:"ailychat@123"
        }
        let _this = this;
        axiosAPI.changePwd(temp)
          .then(function(res){
          if(res.code == "0000"){
            _this.getTableDatas();
          }
        })
      });
    },
    // 提交修改授权信息
    saveUpdateGrants(){
       let _this = this;
      // 更新授权选择的文字
      for(var c1 in this.updateStaffGrantData.grants){
        for(var c2 in this.paramsData.modeGrantUseType){
          if(this.updateStaffGrantData.grants[c1].modeGrantUseTypeCode == this.paramsData.modeGrantUseType[c2].dataValue){
            this.updateStaffGrantData.grants[c1].modeGrantUseTypeName = this.paramsData.modeGrantUseType[c2].dataName;
          }
        }
      }
       axiosAPI.updateStaffGrant(_this.updateStaffGrantData).then(function(res){
         if(res.code == "0000"){
            _this.dialog.grants = false;
            _this.getTableDatas();
         }
       })
    },
    // 授权信息-行编辑修改-是否有日上限选择
    rowIsHaveDayLimitChange(data){
      if(data.isHaveDayLimit==1){// 有日上限
         data.dayLimitCount = 0;
         data.useLess = 0;
      }else{ // 无上限
        data.dayLimitCount = -1;
        data.useLess = -1;
      }
    }
  }
};
</script>

<style scoped></style>
